package Dom4jXML3;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author shkstart
 * @creat 2022-05-21:55
 */
public class ProductXMLParse {
    //扫描器
    public static Scanner scan = new Scanner(System.in);

    public static final String FILE_PATH = "Java_Senior\\d12\\date\\products.xml";


    /**
     * 获取Document对象
     *
     * @return
     * @throws DocumentException
     */
    public static Document getDoc() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(FILE_PATH);
        return doc;
    }

    /**
     * 读取products.xml中的商品信息
     *
     * @return ArrayList
     * @throws DocumentException
     */
    public static List<Product> showProductInfo() throws DocumentException {

        Document doc = getDoc();
        //获取根元素
        Element root = doc.getRootElement();
        //获取根元素下的所有元素
        List<Element> elementList = root.elements("product");
        //ArrayList集合存储product对象
        ArrayList<Product> productList = new ArrayList<>();
        Product product = null;
        for (Element element : elementList) {
            product = new Product();
            String discount = element.attributeValue("discount");
            String factoryAddr = element.attributeValue("factoryaddr");
            String itemNo = element.elementTextTrim("itemno");
            String name = element.elementTextTrim("name");
            String price = element.elementTextTrim("price");
            String stockcount = element.elementTextTrim("stockcount");
            String unit = element.elementTextTrim("unit");
            product.setDiscount(Boolean.parseBoolean(discount));
            product.setFactoryAddr(factoryAddr);
            product.setItemNo(Integer.parseInt(itemNo));
            product.setName(name);
            product.setPrice(Double.parseDouble(price));
            product.setStockCount(Integer.parseInt(stockcount));
            product.setUnit(unit);
            productList.add(product);

        }
        return productList;
    }

    /**
     * 根据输入的商品编号，输出对应的商品信息
     *
     * @param no
     */
    public static Product searchProduct(int no) {
        /*try {
            List<Product> productArrayList = showProductInfo();
            for (Product product : productArrayList) {
                if (product.getItemNo() == no) {
                    //System.out.println(product);
                    return product;
                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;*/
        Document doc = null;
        Product product = null;
        try {
            doc = getDoc();
            //找到了指定编号的商品节点
            Element element = (Element) doc.selectSingleNode("//product[itemno='" + no + "']");
            //创建product对象
            product = new Product();
            //把商品节点转换成对象，并返回对象
            String discount = element.attributeValue("discount");
            String factoryAddr = element.attributeValue("factoryaddr");
            String itemNo = element.elementTextTrim("itemno");
            String name = element.elementTextTrim("name");
            String price = element.elementTextTrim("price");
            String stockcount = element.elementTextTrim("stockcount");
            String unit = element.elementTextTrim("unit");
            product.setDiscount(Boolean.parseBoolean(discount));
            product.setFactoryAddr(factoryAddr);
            product.setItemNo(Integer.parseInt(itemNo));
            product.setName(name);
            product.setPrice(Double.parseDouble(price));
            product.setStockCount(Integer.parseInt(stockcount));
            product.setUnit(unit);
            return product;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把对XML文件的操作保存
     */
    public static void saveXML(Document document) {


        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = null;
        try {
            writer = new XMLWriter(new FileWriter(FILE_PATH), format);
            writer.write(document);
            //刷新缓冲区
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 根据商品编号修改对应的库存量
     *
     * @param no
     * @param stockcount
     */
    public static boolean updateProduct(int no, int stockcount) {

        try {
            Document doc = getDoc();
            Element root = doc.getRootElement();
            List<Element> elements = root.elements();
            Element element1 = elements.stream().filter(element -> element.elementTextTrim("itemno").equals(no + "")).findFirst().orElse(null);
            if (element1 != null) {
                element1.element("stockcount").setText(stockcount + "");
            }
            saveXML(doc);
            return true;


        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 添加新产品，编号和名称都不允许重复
     *
     * @param product
     * @return
     */
    public static boolean addProduct(Product product) {
        Document doc = null;
        try {

            doc = getDoc();
            List<Node> nodeList = doc.selectNodes("//product[itemno]");
            for (Node node : nodeList) {
                Element element = (Element) node;
                if (product.getItemNo() == Integer.parseInt(element.elementText("itemno"))
                        && product.getName().equals(element.elementText("name"))) {
                    return false;
                }
            }
            Element root = doc.getRootElement();
            Element newElement = root.addElement("product");
            newElement.addAttribute("discount", String.valueOf(product.isDiscount()));
            newElement.addAttribute("factoryaddr", product.getFactoryAddr());
            newElement.addElement("itemno").setText(String.valueOf(product.getItemNo()));
            newElement.addElement("name").setText(product.getName());
            newElement.addElement("price").setText(String.valueOf(product.getPrice()));
            newElement.addElement("stockcount").setText(String.valueOf(product.getStockCount()));
            newElement.addElement("unit").setText(product.getUnit());
            saveXML(doc);
            return true;

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 输入商品编号和购买数量，计算应付金额，如果是折扣商品，打七折；
     * 如果购买数量超过库存量，给出提示库存不足，如果购买成功，扣除相应的数量
     *
     * @param no
     * @param count
     * @return
     */
    public static double buyProduct(int no, int count) {
        try {
            Document doc = getDoc();
            Element root = doc.getRootElement();
            List<Element> elements = root.elements();
            double money = 0;
            int newStockCount = 0;
            List<Product> products = showProductInfo();
            for (Product product : products) {
                if (product.getItemNo() == no && product.getStockCount() >= count) {
                    if (product.isDiscount()) {
                        money = product.getPrice() * count * 0.7;
                        newStockCount = product.getStockCount() - count;
                        Element element1 = elements.stream().filter(element ->
                                element.elementTextTrim("itemno").equals(no + "")).findFirst().orElse(null);
                        if (element1 != null) {
                            element1.element("stockcount").setText(newStockCount + "");
                            //element1.selectSingleNode("stockcount").setText(newStockCount + "");
                        }
                        saveXML(doc);
                        return money;
                    } else {
                        money = product.getPrice() * count;
                        newStockCount = product.getStockCount() - count;
                        Element element1 = elements.stream().filter(element ->
                                element.elementTextTrim("itemno").equals(no + "")).findFirst().orElse(null);
                        if (element1 != null) {
                            element1.element("stockcount").setText(newStockCount + "");
                            //element1.selectSingleNode("stockcount").setText(newStockCount + "");
                        }
                        saveXML(doc);

                        return money;
                    }

                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //没有找到商品System.out.println("没有找到" + no + "编号的商品");
        ////或者是库存量不够
        return 0;
    }

    /**
     * 程序的入口
     * @param args
     */
    public static void main(String[] args) {
        exit:
        while (true) {
            System.out.println("\t\t--------------menu-------------");
            System.out.println("\t\t\t<1>全部商品信息");
            System.out.println("\t\t\t<2>查找商品信息");
            System.out.println("\t\t\t<3>修改商品库存");
            System.out.println("\t\t\t<4>增加新商品  ");
            System.out.println("\t\t\t<5>    结账  ");
            System.out.println("\t\t\t<6>    退出  ");
            System.out.println("请选择：");
            int choice = scan.nextInt();
            switch (choice) {
                case 1: {
                    try {
                        List<Product> products = showProductInfo();
                        //遍历productList数组
                        for (Product product1 : products) {
                            System.out.println(product1);
                        }
                    } catch (DocumentException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case 2: {
                    System.out.println("输入商品编号：");
                    int no = scan.nextInt();
                    Product product = searchProduct(no);
                    if (product == null) {
                        System.out.println("没有找到" + no + "编号的商品");
                    }
                    System.out.println("商品信息：");
                    System.out.println(product);
                    break;
                }
                case 3: {
                    System.out.println("输入商品编号：");
                    int no = scan.nextInt();
                    System.out.println("修改库存数量：");
                    int stockCount = scan.nextInt();
                    boolean isSuccess = updateProduct(no, stockCount);
                    if (!isSuccess) {
                        System.out.println("没有找到" + no + "的商品");
                    } else
                        System.out.println(no + "商品库存修改成功！！");
                    break;
                }
                case 4: {
                    System.out.println("输入新商品信息");
                    System.out.println("是否打折：");
                    Boolean discount = scan.nextBoolean();
                    System.out.println("生产厂家");
                    String factoryAddr = scan.next();
                    System.out.println("输入商品编号：");
                    int itemNo = scan.nextInt();
                    System.out.println("输入产品名称：");
                    String name = scan.next();
                    System.out.println("输入价格：");
                    double price = scan.nextDouble();
                    System.out.println("输入计价单位：");
                    String unit = scan.next();
                    System.out.println("输入库存量：");
                    int stockCount = scan.nextInt();
                    Product product = new Product(discount, factoryAddr, itemNo, name, price, unit, stockCount);
                    boolean isSuccess = addProduct(product);
                    if (!isSuccess) {
                        System.out.println("商品已存在！！");
                    } else
                        System.out.println("加入成功！！");
                    break;
                }
                case 5: {
                    System.out.println("输入商品编号：");
                    int no2 = scan.nextInt();
                    System.out.println("输入购买数量：");
                    int count = scan.nextInt();
                    double money = buyProduct(no2, count);
                    if (money > 0) {
                        System.out.println("您一共消费" + money + "元");
                    } else {
                        System.out.println("库存不足或没找到商品");
                    }
                    break;
                }
                case 6: {
                    System.out.println("欢迎下次光临！");
                    break exit;
                }

            }

        }
    }
}
